import urllib,urllib2,re,xbmcplugin,xbmcgui,os

###################################################################################
##
##      EzTV - Torrent Download Plugin
##      -------------------------------------
##      0.1  - First version with only basic Navigation
###################################################################################
##      Todo:
##      - Error Checking
##      - Extended Labels Info
##      - Text Search
##      - TV Show Search
###################################################################################

MyPath  = os.getcwd()
MyMedia = MyPath +'\\media'

## Variable Set Refresh or No Refresh
DirRefresh = False

def Comms(url):
        ## Standard code
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        response = urllib2.urlopen(req)
        link=response.read()
        response.close()
        return link

        
def LIST(url):
        ## Get html data
        link = Comms(url)

        ## Get Whole Lines
        Exp = re.compile('<tr.*?>(.*?)</tr>',re.DOTALL)     
        Tar = re.findall(Exp,link)

        Records = 0

        ## Get Each Row
        for i in Tar:
            Pex = re.compile('<td.*?>(.*?)</td>',re.DOTALL)
            Tas = re.findall(Pex,i)

            ## 10 means all the available parts of the form are present.
            if len(Tas) == 10:
                ## Check that this is not the Header column.
                if Tas[4] != "Size":
                        
                    Records     = Records + 1
                    Exp         = re.compile('(http://.*?\.torrent).*?alt=\"Download (.*?)\"',re.DOTALL)
                
                    xLink       = re.findall(Exp,Tas[1])[0][0]
                    xName       = re.findall(Exp,Tas[1])[0][1]
                    xGroup      = Tas[3]
                    xSize       = Tas[4]        
                    xSeeds      = Tas[5]
                    xPeers      = Tas[6]
                    xCompleted  = Tas[7]
                    xAge        = Tas[8]

                    xLabel2 = 'Size: ' + xSize + ' | Seeds: ' + xSeeds + '(' + xPeers + ') | Age: ' + xAge
                    if xSeeds <= 10:
                            xHealth = MyMedia + '\Health-1.png'
                    elif xSeeds >= 100:
                            xHealth = MyMedia + '\Health-3.png'
                    else:
                            xHealth = MyMedia + '\Health-2.png'

                    ## Now call the Routine to add the Labels:
                    addDir(xName, xLabel2 ,xLink,2, xHealth)
        

def SaveFiles(name,url)  :
        ## Create static directory locations.
        RootPath = "special://profile/torrents/"
        
        if not os.path.exists(RootPath):
                os.mkdir(RootPath)

        NewName = NiceName(name)
        FullPath = RootPath + NewName

        ## Get html data
        link = Comms(url)
                
        ## Save The file
        f   =   open(str(FullPath),'wb')
        f.write(link)
        f.close()
                

def NiceName(fName):
        NewName     =   ''
        tName       =   fName.rsplit('.',1)
        xName       =   tName[0][:30]
        if ( xName[0].isdigit() )   :
                xName = 'x'+ str(xName)
        for xChar in xName                  :
                if      xChar.isalnum()         :   NewName  += str(xChar)
                elif    xChar.isspace()         :   NewName  += '_'
                else                            :   pass
        if len(NewName) > 4                 :
                return NewName +'.torrent'
        else                                :
                return None



def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param



def addDir(name,label, url,mode,iconimage):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, label, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok
        
              
params=get_params()
url=None
name=None
mode=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass

print "Mode: "+str(mode)
print "URL: "+str(url)
print "Name: "+str(name)

if mode==None or url==None or len(url)<1:
        LIST('http://eztv.it/index.php?main=main&sort=2')


if mode==2:
        SaveFiles(urllib.unquote_plus(params["name"]),urllib.unquote_plus(params["url"]))
        LIST('http://eztv.it/index.php?main=main&sort=2')
        DirRefresh = True
        

xbmcplugin.addSortMethod(int(sys.argv[1]), 0)
xbmcplugin.endOfDirectory(int(sys.argv[1]),updateListing=DirRefresh)

